#include "designmodel.h"
#include "designitem.h"


#include <datasuite.h>


DesignModel::DesignModel(QObject *parent) :
    ItemTreeModel(parent)
{
}

int DesignModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    DesignItem* root = qobject_cast<DesignItem*>(m_root);
    if (!root) return 0;

    int ret = 0;
    foreach (DesignItem* item, root->findChildren<DesignItem*>())
    {
        if (item->fieldCount() <= ret)
        {
            continue;
        }

        ret = item->fieldCount();
    }

    return ret;
}


bool DesignModel::insertRows(int type, int count, const QModelIndex &parent)
{
    return ItemTreeModel::insertRows(type, count, parent);
}


bool DesignModel::insertColumns(int row, int count, const QModelIndex &parent)
{
    Q_UNUSED(count)

    QModelIndex itemIndex = index(row, 0, parent);
    DesignItem* item = qobject_cast<DesignItem*>(itemFromIndex(itemIndex));
    if (!item || !item->container())
    {
        return false;
    }

    int cols = item->container()->fieldCount();

//    qDebug() << Q_FUNC_INFO << "- New column index:" << cols;

    beginInsertColumns(parent, cols, cols);
    item->container()->addField(QString("field%1").arg(cols));
    endInsertColumns();

    emit dataChanged(itemIndex, itemIndex.sibling(itemIndex.row(), cols));
    emit headerDataChanged(Qt::Horizontal, 0, cols);

    return true;
}


Qt::ItemFlags DesignModel::flags(const QModelIndex &index) const
{
    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}


int DesignModel::fieldCount(const QModelIndex &index) const
{
    DesignItem* item = qobject_cast<DesignItem*>(itemFromIndex(index));
    if (!item || !item->container())
    {
        return 1;
    }

    return item->container()->fieldCount()+1;
}

QVariant DesignModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_UNUSED(orientation);
    if (role != Qt::DisplayRole) return QVariant();

//    switch (section)
//    {
//    case DataContainer::Field_NAME:
//        return tr("Name");

//    default:
//        break;
//    }

    return QString("%1 %2").arg(tr("Field")).arg(section);
}


